package com.biShe.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.biShe.entity.*;
import com.biShe.mapper.BuyedGoodsMapper;
import com.biShe.mapper.OrdersCBuyedGoodsMapper;
import com.biShe.mapper.OrdersMapper;
import com.biShe.mapper.StoreMapper;
import com.biShe.utils.Result;
import com.biShe.vo.MyOrderVO;
import com.biShe.vo.OrdersVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 小刘
 * @since 2023-05-10
 */
@Configuration
@RestController
@RequestMapping("/orders")
public class OrdersController {

    @Autowired
    OrdersMapper ordersMapper;

    @Autowired
    StoreMapper storeMapper;

    //连接表
    @Autowired
    OrdersCBuyedGoodsMapper ordersCBuyedGoodsMapper;

    @Autowired
    BuyedGoodsMapper buyedGoodsMapper;



    @ApiOperation(value="根据订单Id获取订单信息", notes="返回指定Id的订单信息")
    @ApiImplicitParam(name = "id",value = "订单id", required = true, dataType = "Int", paramType = "path")
    @GetMapping("/myorders/{openId}/{id}")
    public Result getOrdersVO(@PathVariable("openId") String openId, @PathVariable("id") Integer id) {
        MyOrderVO myOrderVO = new MyOrderVO();
        OrdersVO ordersVO = new OrdersVO();
        ordersVO = getOrdersVO(openId);
        List<MyOrderVO> myOrderVOS = ordersVO.getMyOrderVOS();
        for (MyOrderVO mo:myOrderVOS){
            if(mo.getId() == id){
                myOrderVO = mo;
            }
        }
        if (myOrderVO == null){

            return Result.fail("该订单不存在");
        }
        return Result.succ(myOrderVO);
    }



    @ApiOperation(value="根据openId获取订单信息", notes="返回指定openId的订单信息")
    @ApiImplicitParam(name = "openId", value = "微信openId", required = true, dataType = "String", paramType = "path")
    @GetMapping("/myorders/{openId}")
    public OrdersVO getOrdersVO(@PathVariable("openId") String openId){
        OrdersVO ordersVO = new OrdersVO();


        List<MyOrderVO> myOrderVOS = new ArrayList<>();

        QueryWrapper<Orders> ordersQueryWrapper = new QueryWrapper<>();
        ordersQueryWrapper.eq("openId",openId);
        //查询出该openID用户的所有订单,给第一层的属性赋值，一个对象就是OrdersVo里的一个单条数据
        List<Orders> orders1 = ordersMapper.selectList(ordersQueryWrapper);
        for (Orders od:orders1){
            MyOrderVO myOrderVO = new MyOrderVO();
            BeanUtils.copyProperties(od,myOrderVO);//先把相同的属性复制一份

            //放入店铺的对象信息
            QueryWrapper<Store> storeQueryWrapper = new QueryWrapper<>();
            storeQueryWrapper.eq("id",od.getStoreId());
            Store store1 = storeMapper.selectOne(storeQueryWrapper);
            myOrderVO.setStore(store1);

            //放入购买的商品信息
            List<BuyedGoods> goods1 = new ArrayList<>();
            //取出这条订单的id，去连接表里找orders_id等于id的list，再取出对应的buyed_goods_id，去buyed_goods_id里查找数据，获得的list就是这里需要的
            QueryWrapper<OrdersCBuyedGoods> ordersCBuyedGoodsQueryWrapper = new QueryWrapper<>();
            ordersCBuyedGoodsQueryWrapper.eq("orders_id",od.getId());
            List<OrdersCBuyedGoods> ordersCBuyedGoods = ordersCBuyedGoodsMapper.selectList(ordersCBuyedGoodsQueryWrapper);
            for (OrdersCBuyedGoods ocb:ordersCBuyedGoods){
                // 取出对应的buyed_goods_id，去buyed_goods里查找数据,查到一条，就放到goods里
                QueryWrapper<BuyedGoods> buyedGoodsQueryWrapper = new QueryWrapper<>();
                buyedGoodsQueryWrapper.eq("id",ocb.getBuyedGoodsId());
                BuyedGoods buyedGoods1 = buyedGoodsMapper.selectOne(buyedGoodsQueryWrapper);

                goods1.add(buyedGoods1);
            }
            myOrderVO.setGoods(goods1);
            //把一条装配完整的订单，放入列表里
            myOrderVOS.add(myOrderVO);
        }


        ordersVO.setMyOrderVOS(myOrderVOS);

        return ordersVO;
    }



    @ApiOperation(value="添加订单信息", notes="向系统的相关表中添加订单信息")
    @ApiImplicitParam(name = "myOrderVO", value = "需要添加的订单信息", required = true, dataType = "MyOrderVO")
    @PostMapping("/add/myorders")
    public Result add(@RequestBody  MyOrderVO myOrderVO){
        Orders orders1 = new Orders();
        BeanUtils.copyProperties(myOrderVO,orders1);//先把相同的属性复制一份,插入order表
        int rows1= ordersMapper.insert(orders1);

        //把购物车里的信息插入关系表和buyed表，先插buyed表
        List<BuyedGoods> buyedGoods = myOrderVO.getGoods();
        for (BuyedGoods bg:buyedGoods){
            int rows2 = buyedGoodsMapper.insert(bg);
            if (rows2 == 0) {
                //撤回数据库的所有操作
                return Result.fail("添加已购买商品信息失败");
            }
        }

        //插关系表,先查出刚插入的订单id（一对多），再查出刚刚插入的被买商品id（用下单时间，时间应该是唯一的）
//        QueryWrapper<Orders> ordersQueryWrapper = new QueryWrapper<>();
//        ordersQueryWrapper.eq("order_no",myOrderVO.getOrderNo());
//        Orders order2 = ordersMapper.selectOne(ordersQueryWrapper);//订单id在里面

        QueryWrapper<BuyedGoods> buyedGoodsQueryWrapper = new QueryWrapper<>();
        buyedGoodsQueryWrapper.eq("created_time",myOrderVO.getCreatedAt());
        List<BuyedGoods> mygoods = buyedGoodsMapper.selectList(buyedGoodsQueryWrapper);
        for (BuyedGoods buyedGoodsConnect:mygoods){
            OrdersCBuyedGoods ordersCBuyedGoods = new OrdersCBuyedGoods();
            ordersCBuyedGoods.setOrdersId(orders1.getId());
            ordersCBuyedGoods.setBuyedGoodsId(buyedGoodsConnect.getId());

            int rows3 = ordersCBuyedGoodsMapper.insert(ordersCBuyedGoods);
            if (rows3 == 0) {
                //撤回数据库的所有操作
                return Result.fail("添加已购买商品_订单关系表信息失败");
            }

        }


        //事务？回滚？
        if (rows1 == 0) {
            //撤回数据库的所有操作
            return Result.fail("添加订单失败");
        }


//    getOrdersVO
        MyOrderVO VO1 = new MyOrderVO();
        Result result1 = getOrdersVO(myOrderVO.getOpenid(),orders1.getId());//查询插入结果返回前端
        VO1 = (MyOrderVO) result1.getData();


        return Result.succ(VO1);
    }


    /**
     * 更新订单信息，店员，调用该方法，制作中，修改订单状态为2制作中
     *
     * @param id 订单id
     * @return 返回更新结果
     */
    @ApiOperation(value="修改订单信息为制作中", notes="修改指定订单的信息为制作中")
    @ApiImplicitParam(name = "id", value = "订单id", required = true, dataType = "Int")
    @PutMapping("/update2")
    public Result update2(@RequestParam Integer id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(2);
        orders.setStatusText("制作中");
        int rows = ordersMapper.updateById(orders);
        if (rows == 0) {
            return Result.fail("制作中，更新失败");
        }
        return Result.succ("制作中，更新成功");
    }



    /**
     * 更新订单信息，店员，调用该方法，制作完成，外卖，修改订单状态为3 1已下单 2制作中  3待取货（等待骑手拿） 4外卖配送中（骑手拿到货） 5已完成”
     *
     * @param id 订单id
     * @return 返回更新结果
     */
    @ApiOperation(value="修改订单信息外卖制作完成（待取货）", notes="修改指定订单的信息外卖制作完成（待取货）")
    @ApiImplicitParam(name = "id", value = "订单id", required = true, dataType = "Int")
    @PutMapping("/update3")
    public Result update3(@RequestParam Integer id) {
        //获取时间戳
        long l = System.currentTimeMillis();

        //格式化
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String s = format.format(l);
        System.out.println(s);
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(3);
        orders.setStatusText("请取餐");
        orders.setProductionedTime(s);
        int rows = ordersMapper.updateById(orders);
        if (rows == 0) {
            return Result.fail("订单制作完成（请取餐），更新失败");
        }
        return Result.succ("订单制作完成（请取餐），更新成功");
    }


    /**
     * 更新订单信息，骑手，调用该方法，制作完成，外卖取货，修改订单状态为4 1已下单 2制作中  3待取货（等待骑手拿） 4外卖配送中（骑手拿到货） 5已完成”
     *
     * @param id 订单id
     * @return 返回更新结果
     */
    @ApiOperation(value="修改订单信息,骑手取餐，配送状态", notes="修改指定订单的信息,骑手取餐，配送状态")
    @ApiImplicitParam(name = "id", value = "订单id", required = true, dataType = "Int")
    @PutMapping("/update4")
    public Result update4(@RequestParam Integer id) {
        //获取时间戳
        long l = System.currentTimeMillis();

        //格式化
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String s = format.format(l);
        System.out.println(s);
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(4);
        orders.setStatusText("外卖配送中");
        orders.setTakedTime(s);
        int rows = ordersMapper.updateById(orders);
        if (rows == 0) {
            return Result.fail("骑手取餐，配送状态更新失败");
        }
        return Result.succ("骑手取餐，配送状态更新成功");
    }

    /**
     * 更新订单信息，骑手，调用该方法，制作完成，店内取餐，修改订单状态为5 1已下单  3请取餐（店内）4外卖配送中（骑手拿到货的时间） 5已完成”
     *
     * @param  id 订单id
     * @return 返回更新结果
     */
    @ApiOperation(value="修改订单信息,送餐完成/店内取餐制作完成", notes="修改指定订单的信息,送餐完成")
    @ApiImplicitParam(name = "id", value = "订单id", required = true, dataType = "Int")
    @PutMapping("/update5")
    public Result update5(@RequestParam Integer id) {
        //获取时间戳
        long l = System.currentTimeMillis();

        //格式化
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String s = format.format(l);
        System.out.println(s);
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(5);
        orders.setStatusText("已完成");
        orders.setCompletedTime(s);
        int rows = ordersMapper.updateById(orders);
        if (rows == 0) {
            return Result.fail("送餐完成，配送状态更新失败");
        }
        return Result.succ("送餐完成，配送状态更新成功");
    }


    /**

     按条件查询订单信息
    takein
     @return 返回符合要求的订单id
     */
    @ApiOperation(value="按条件查询订单信息，店内取餐制作", notes="查询orderType为takein且created_at字段中时间最早的订单id")
    @GetMapping("/getEarliestOrderIn")
    public Result getEarliestOrder() {
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.eq("status",1);
        wrapper.eq("orderType", "takein");
        wrapper.orderByAsc("created_at");
        wrapper.last("limit 1");

        Orders order = ordersMapper.selectOne(wrapper);
        if (order == null) {
            return Result.fail("未查询到符合要求的订单");
        }
        Integer orderId = order.getId();
        return Result.succ(order);
    }

    /**

     按条件查询订单信息
     takeout
     @return 返回符合要求的订单id
     */
    @ApiOperation(value="按条件查询订单信息，外卖制作", notes="查询orderType为takein且created_at字段中时间最早的订单id")
    @GetMapping("/getEarliestOrderOut")
    public Result getEarliestOrder2() {
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.eq("status",1);
        wrapper.eq("orderType", "takeout");
        wrapper.orderByAsc("created_at");
        wrapper.last("limit 1");

        Orders order = ordersMapper.selectOne(wrapper);
        if (order == null) {
            return Result.fail("未查询到符合要求的订单");
        }
        Integer orderId = order.getId();
        return Result.succ(order);
    }


    /**
     * 查找所有订单
     *
     * @return 返回所有订单信息列表
     */
    @ApiOperation(value="获取所有订单信息", notes="返回所有订单列表")
    @GetMapping("/list/{page}/{size}")
    public Result list(@PathVariable("page") String page, @PathVariable("size") String size) {
        Page pageHelper = PageHelper.startPage(Integer.parseInt(page),Integer.parseInt(size));
        List<Orders> categoryList = ordersMapper.selectList(null);
        PageInfo pageInfo = new PageInfo(categoryList);
        return Result.succ(pageInfo);
    }


        /**
         * 获取所有订单信息
         *
         * @param page 当前页数
         * @param size 每页数量
         * @param orderType 订单类型
         * @param goodsNum 商品数
         * @return 订单信息列表
         */
        @GetMapping("/list")
        public Result list(@RequestParam(defaultValue = "1") String page,
                                 @RequestParam(defaultValue = "5") String size,
                                 @RequestParam(required = false) String orderType,
                                 @RequestParam(required = false) Integer goodsNum) {
            Page pageHelper = PageHelper.startPage(Integer.parseInt(page),Integer.parseInt(size));
            QueryWrapper<Orders> wrapper = null;
            if (orderType != null || goodsNum != null) {
                wrapper = new QueryWrapper<>();
                if (orderType != null) {
                    wrapper.eq("order_type", orderType);
                }
                if (goodsNum != null) {
                    wrapper.eq("goods_num", goodsNum);
                }
//                if (remarkExist != null) {
//                    if (remarkExist) {
//                        wrapper.isNotNull("remark");
//                    } else {
//                        wrapper.isNull("remark");
//                    }
//                }
//                if (filterValue != null && !"".equals(filterValue.trim())) {
//                    switch (filterType) {
//                        case "order_no":
//                            wrapper.like("order_no", filterValue);
//                            break;
//                        case "user_name":
//                            wrapper.like("user_name", filterValue);
//                            break;
//                        case "mobile":
//                            wrapper.like("mobile", filterValue);
//                            break;
//                        case "remark":
//                            wrapper.like("remark", filterValue);
//                            break;
//                        default:
//                            break;
//                    }
//                }
            }
            List<Orders> mylist = ordersMapper.selectList(wrapper);
            PageInfo pageInfo = new PageInfo(mylist);
            return Result.succ(pageInfo);
        }
    }

//
//    /**
//     * 根据订单名模糊查询订单信息
//     *
//     * @param name 订单名
//     * @return 返回符合条件的订单信息列表
//     */
//    @ApiOperation(value="根据订单名模糊查询订单信息", notes="返回符合条件的订单信息列表")
//    @ApiImplicitParam(name = "name", value = "名", required = true, dataType = "String", paramType = "path")
//    @GetMapping("/search/{name}")
//    public Result search(@PathVariable("name") String name) {
//        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
//        wrapper.like("name", name);
//        List<Orders> categoryList = ordersMapper.selectList(wrapper);
//        if (categoryList.isEmpty()) {
//            return Result.fail("暂无匹配结果");
//        }
//        return Result.succ(categoryList);
//    }









